package com.ruoyi.system.handler;

import com.ruoyi.common.core.domain.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.concurrent.CompletionException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;

/**
 * 全局异步任务异常处理器
 * 处理CompletableFuture相关的异常
 */
@RestControllerAdvice
@Slf4j
@Component
public class AsyncExceptionHandler {
    
    /**
     * 处理超时异常
     * @param ex TimeoutException
     * @return AjaxResult
     */
    @ExceptionHandler(TimeoutException.class)
    public AjaxResult handleTimeoutException(TimeoutException ex) {
        log.error("异步任务超时", ex);
        return AjaxResult.error("操作超时，请稍后重试");
    }
    
    /**
     * 处理执行异常
     * @param ex ExecutionException
     * @return AjaxResult
     */
    @ExceptionHandler(ExecutionException.class)
    public AjaxResult handleExecutionException(ExecutionException ex) {
        log.error("异步任务执行异常", ex);
        return AjaxResult.error("操作执行异常: " + ex.getCause().getMessage());
    }
    
    /**
     * 处理中断异常
     * @param ex InterruptedException
     * @return AjaxResult
     */
    @ExceptionHandler(InterruptedException.class)
    public AjaxResult handleInterruptedException(InterruptedException ex) {
        log.error("异步任务被中断", ex);
        Thread.currentThread().interrupt(); // 重新设置中断标志
        return AjaxResult.error("操作被中断");
    }
    
    /**
     * 处理所有未捕获的异步异常
     * @param ex Exception
     * @return AjaxResult
     */
    @ExceptionHandler(Exception.class)
    public AjaxResult handleAllUncaughtExceptions(Exception ex) {
        log.error("捕获到未处理的异常", ex);
        if (ex instanceof CompletionException || ex instanceof ExecutionException) {
            return AjaxResult.error("异步任务异常: " + ex.getCause().getMessage());
        }
        return AjaxResult.error("系统异常: " + ex.getMessage());
    }
}